package com.yitongmao.core.network.service;


import com.alibaba.sdk.android.oss_android_sdk.BuildConfig;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.common.FileUtils;
import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.glide.ProgressListener;
import com.yitongmao.core.glide.ProgressResponseBody;
import com.yitongmao.core.network.api.BaseApiInterface;
import com.yitongmao.core.network.api.ToMediaConverterFactory;
import com.yitongmao.core.network.api.gosn.GsonConverterFactory;
import com.yitongmao.util.Loger;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BaseProgressService {

    private volatile static BaseProgressService instance;
    public static OkHttpClient httpClient;
    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(BuildConfig.APPLICATION_ID)
                    .addConverterFactory(new ToMediaConverterFactory())
                    .addConverterFactory(GsonConverterFactory.create());
    public ACache mCache;
    BaseApiInterface baseApiInterface;
//    private WeakReference<HashMap<String, Call>> mapWeakReference;
    private HashMap<String, Call> callHashMap = new HashMap<String, Call>();

    private BaseProgressService(ProgressListener progressListener) {
        mCache = ACache.get(ReaderApplication.applicationContext);
//        ApiGenerator.httpClient = GlideProgressListener.getGlideOkHttpClient(progressListener);
        baseApiInterface = createApiClients(BaseApiInterface.class,null,null,progressListener);
//        mapWeakReference = new WeakReference<HashMap<String, Call>>(callHashMap);

    }

    public static BaseProgressService getInstance(ProgressListener progressListener) {
        if (instance == null) {
            synchronized (BaseProgressService.class) {
                if (instance == null) {
                    instance = new BaseProgressService(progressListener);
                }
            }
        }
        return instance;
    }


    public void downloadNewVersionFile(String url, final String fileName, final CallBackListener callBackListener) {
        callBackListener.onStart();
        Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                Loger.i("downloadFile", "downloadFile-onResponse-" + response.body().byteStream());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File file = FileUtils.write2SDFromInput(fileName, response.body().byteStream());
                        Loger.i("downloadFile", "-downloadFile-" + file.getAbsolutePath());
                        if (file.exists()) {
                            Loger.i("downloadFile", "-downloadFile-0");
                            callBackListener.onSuccess(file.getPath());
                        } else {
                            Loger.i("downloadFile", "-downloadFile-1");
                            callBackListener.onFail(response.errorBody());
                        }
                    }
                }).start();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBackListener.onFail(t.toString());
            }
        });
    }


    public static <T> T createApiClients(Class<T> serviceClass, String baseUrl, HashMap headers,final ProgressListener progressListener) {
        if (!isEmptry(baseUrl)) {
            builder =
                    new Retrofit.Builder()
                            .baseUrl(baseUrl)
                            .addConverterFactory(new ToMediaConverterFactory())
                            .addConverterFactory(GsonConverterFactory.create());
        }

        // add download Interceptor
        if (progressListener != null) {
            Loger.i("createApiClient","createApiClient-------0--------");
//            httpClient.newBuilder().addNetworkInterceptor(new DownloadProgressInterceptor(progressListener)).build();
            httpClient = new OkHttpClient().newBuilder().addNetworkInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Loger.i("createApiClient","createApiClient-------1--------");
                    okhttp3.Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder()
                            .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                            .build();
                }
            }).build();
        }
        Retrofit retrofit = builder.client(httpClient).build();
        return retrofit.create(serviceClass);
    }
    public static boolean isEmptry(CharSequence str) {
        return str == null || str.length() == 0 || "null".equalsIgnoreCase(str.toString());

    }

}
